<template>
    <view class="register-container">
        <view class="header" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
            <text class="title">用户注册</text>
        </view>

        <!-- #ifdef MP-WEIXIN -->
        <view class="form-container">
            <view class="form-group">
                <input
                    class="input"
                    type="text"
                    placeholder="请输入用户名"
                    v-model="formData.username"
                />
                <input
                    class="input"
                    password
                    placeholder="请输入密码"
                    v-model="formData.password"
                />
                <input
                    class="input"
                    password
                    placeholder="请确认密码"
                    v-model="formData.confirmPassword"
                />
            </view>
            <button 
                class="register-btn"
                :loading="loading"
                @click="handleMiniRegister"
            >立即注册</button>
        </view>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <view class="tab-bar">
            <text 
                :class="['tab-item', activeTab === 0 && 'active']"
                @click="activeTab = 0"
            >账号注册</text>
            <text 
                :class="['tab-item', activeTab === 1 && 'active']"
                @click="activeTab = 1"
            >手机注册</text>
        </view>

        <view class="form-container">
            <view v-if="activeTab === 0" class="form-group">
                <input
                    class="input"
                    type="text"
                    placeholder="请输入用户名"
                    v-model="formData.username"
                />
                <input
                    class="input"
                    password
                    placeholder="请输入密码"
                    v-model="formData.password"
                />
                <input
                    class="input"
                    password
                    placeholder="请确认密码"
                    v-model="formData.confirmPassword"
                />
            </view>

            <view v-if="activeTab === 1" class="form-group">
                <input
                    class="input"
                    type="number"
                    placeholder="请输入手机号"
                    v-model="formData.phone"
                    maxlength="11"
                />
                <view class="code-input">
                    <input
                        class="input"
                        type="number"
                        placeholder="请输入验证码"
                        v-model="formData.code"
                    />
                    <text 
                        class="get-code"
                        :class="{ 'disabled': codeCountdown > 0 }"
                        @click="getSmsCode"
                    >{{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}</text>
                </view>
                <input
                    class="input"
                    password
                    placeholder="请输入密码"
                    v-model="formData.password"
                />
            </view>
            <button 
                class="register-btn"
                :loading="loading"
                @click="handleH5Register"
            >立即注册</button>
        </view>
        <!-- #endif -->

        <view v-if="message" :class="['message', messageType]">
            {{ message }}
        </view>
        
        <view class="login" @click="goToLogin">已有账号？立即登录</view>
    </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import localData from '@/static/db/index.json'

const { safeAreaInsets } = uni.getSystemInfoSync()

// 响应式数据
const loading = ref(false)
const codeCountdown = ref(0)
const message = ref('')
const messageType = ref('success')
// #ifdef H5
const activeTab = ref(0)
// #endif

const formData = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    code: ''
})

// H5注册处理
const handleH5Register = async () => {
    if (activeTab.value === 0) {
        // 账号注册验证
        if (!formData.username || !formData.password || !formData.confirmPassword) {
            return showMessage('请填写完整信息')
        }
        if (formData.password !== formData.confirmPassword) {
            return showMessage('两次密码不一致')
        }
        if (formData.password.length < 6) {
            return showMessage('密码长度至少6位')
        }

        try {
            // 检查用户名是否已存在
            axios.post('http://localhost:3000/add_user',formData).then(res=>{
                if(res.data.code==401){
                    return showMessage(res.data.message)
                }
                if(res.data.code==200){
                    uni.navigateTo({url:'/pages/Login/Login'})
                }
            })
            // const userExists = localData.users.some(u => u.username === formData.username)
            // if (userExists) {
            //     return showMessage('用户名已存在')
            // }

            // // 模拟注册成功
            // const newUser = {
            //     id: localData.users.length + 1,
            //     username: formData.username,
            //     password: formData.password
            // }
            // showMessage('注册成功', 'success')
            
            // // 模拟保存数据（实际项目中应调用API）
            // localData.users.push(newUser)
            
            // // 自动登录并跳转
            // uni.setStorageSync('userInfo', newUser)
            // setTimeout(() => {
            //     uni.switchTab({ url: '/pages/index/index' })
            // }, 1500)
        } catch (error) {
            handleRegisterError(error)
        }
    } else {
        // 手机号注册验证
        if (!formData.phone || !formData.code || !formData.password) {
            return showMessage('请填写完整信息')
        }
        if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
            return showMessage('手机号格式错误')
        }

        try {
            const response = await axios.post('http://localhost:3001/register/phone', {
                phone: formData.phone,
                code: formData.code,
                password: formData.password
            })
            handleRegisterSuccess(response)
        } catch (error) {
            handleRegisterError(error)
        }
    }
}

// 获取验证码（与登录页相同逻辑）
const getSmsCode = async () => {
    if (codeCountdown.value > 0) return
    
    if (!formData.phone) {
        return showMessage('请输入手机号')
    }

    loading.value = true
    try {
        const response = await axios.post('http://localhost:3001/send-sms', {
            phoneNumber: formData.phone
        })

        if (response.data.success) {
            showMessage('验证码发送成功', 'success')
            codeCountdown.value = 60
            const timer = setInterval(() => {
                if (codeCountdown.value <= 0) {
                    clearInterval(timer)
                    return
                }
                codeCountdown.value--
            }, 1000)
        } else {
            showMessage(response.data.message || '验证码发送失败')
        }
    } catch (error) {
        showMessage('发送失败，请重试')
    } finally {
        loading.value = false
    }
}

// 小程序注册处理
const handleMiniRegister = async () => {
    if (!formData.username || !formData.password || !formData.confirmPassword) {
        return showMessage('请填写完整信息')
    }
    if (formData.password !== formData.confirmPassword) {
        return showMessage('两次密码不一致')
    }

    loading.value = true
    try {
        // 检查用户名是否已存在
        const userExists = localData.users.some(u => u.username === formData.username)
        if (userExists) {
            return showMessage('用户名已存在')
        }

        // 模拟注册成功
        const newUser = {
            id: localData.users.length + 1,
            username: formData.username,
            password: formData.password
        }
        
        localData.users.push(newUser)
        showMessage('注册成功', 'success')
        
        // 自动登录
        uni.setStorageSync('userInfo', newUser)
        setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
        }, 1500)
    } catch (error) {
        console.error('注册失败:', error)
        showMessage('注册失败，请重试')
    } finally {
        loading.value = false
    }
}

// 统一处理注册成功
const handleRegisterSuccess = (response) => {
    if (response.data.success) {
        showMessage('注册成功', 'success')
        uni.setStorageSync('userInfo', response.data.user)
        setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
        }, 1500)
    } else {
        showMessage(response.data.message || '注册失败')
    }
}

// 统一处理注册错误
const handleRegisterError = (error) => {
    console.error('注册失败:', error)
    showMessage(error.response?.data?.message || '注册失败，请重试')
}

// 显示消息提示
const showMessage = (msg, type = 'error') => {
    message.value = msg
    messageType.value = type
    setTimeout(() => {
        message.value = ''
    }, 3000)
}

const goToLogin = () => {
    uni.navigateTo({ url: '/pages/Login/Login' })
}
</script>

<style lang="scss" scoped>
.register-container {
    min-height: 100vh;
    background: #f8f8f8;
    
    .header {
        height: 240rpx;
        background: #00c8aa;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .title {
            color: #fff;
            font-size: 40rpx;
            font-weight: bold;
        }
    }
    
    .tab-bar {
        display: flex;
        justify-content: center;
        margin: 40rpx 0;
        
        .tab-item {
            margin: 0 40rpx;
            font-size: 32rpx;
            color: #666;
            padding-bottom: 10rpx;
            
            &.active {
                color: #00c8aa;
                border-bottom: 4rpx solid #00c8aa;
            }
        }
    }
    
    .form-container {
        padding: 0 60rpx;
        
        .form-group {
            margin-bottom: 60rpx;
            
            .input {
                height: 100rpx;
                background: #fff;
                margin-bottom: 30rpx;
                padding: 0 30rpx;
                border-radius: 12rpx;
                font-size: 28rpx;
            }
            
            .code-input {
                position: relative;
                
                .get-code {
                    position: absolute;
                    right: 20rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    color: #00c8aa;
                    font-size: 28rpx;
                    
                    &.disabled {
                        color: #999;
                    }
                }
            }
        }
        
        .register-btn {
            height: 90rpx;
            line-height: 90rpx;
            background: #00c8aa;
            color: #fff;
            font-size: 32rpx;
            border-radius: 45rpx;
        }
    }
    
    .message {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        padding: 20rpx 40rpx;
        border-radius: 10rpx;
        font-size: 28rpx;
        z-index: 999;
        
        &.success {
            background: rgba(0, 200, 170, 0.9);
            color: #fff;
        }
        
        &.error {
            background: rgba(255, 0, 0, 0.9);
            color: #fff;
        }
    }
    
    .login {
        width: 100%;
        text-align: center;
        margin-top: 40rpx;
        color: #00c8aa;
        font-size: 28rpx;
    }
}
</style>
